package com.service.purchase;

import com.alibaba.excel.EasyExcel;
import com.common.DateUtils;
import com.common.StringUtils;
import com.common.easyui.EasyuiUtils;
import com.common.http.HttpResult;
import com.common.http.HttpStatus;
import com.common.model.Global;
import com.common.spring.SpringMvcUtils;
import com.dao.purchase.*;
import com.dao.supply.InfoMapper;
import com.enums.OfferModeEnum;
import com.model.purchase.*;
import com.model.supply.SupplyInfoModel;
import com.model.sys.SysUser;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * 询价书
 * 
 * @author chenjun
 *
 */
@Service
public class InquiryService {

	static final Logger logger = LoggerFactory.getLogger(InquiryService.class);

	@Autowired
	InquiryMapper inquiryMapper;
	@Autowired
	SupplyOfferMapper supplyOfferMapper;
	@Autowired
	SupplyOfferMmMapper supplyOfferMmMapper;
	@Autowired
	ProgramMmMapper programMmMapper;
	@Autowired
	PurchaseMapper purchaseMapper;
	@Autowired
	CommonService commonService;
	@Autowired
	ProgramMapper programMapper;
	@Autowired
	InfoMapper infoMapper;
	@Autowired
	SupplyCompeteDao supplyCompeteDao;
	@Autowired
	SupplyCompeteMmDao supplyCompeteMmDao;

	/**
	 * 询价列表查询
	 *
	 * @param queryMap
	 * @return
	 */
	public HttpResult selectInquiryList(Map<String, Object> queryMap) {
		HttpResult httpResult = new HttpResult();
		EasyuiUtils.addPageNum(queryMap);
		EasyuiUtils.addFilter(queryMap);
		SysUser sysUser = SpringMvcUtils.getSysUser();

		if (!sysUser.getSuperadmin().equals(Global.YES + "")) {
			if (StringUtils.isNotNull(sysUser.getDatapermission())) {
				queryMap.put("deptIds", sysUser.getDatapermission().split(","));
			} else {
				queryMap.put("createId", sysUser.getUserid());
			}
		}
		List<PurchaseInquiry> list = inquiryMapper.selectInquiryList(queryMap);
		int count = inquiryMapper.selectInquiryListCount(queryMap);
		httpResult.setRows(list);
		httpResult.setTotal(count);
		logger.info("selectInquiryList:{}", list);

		return httpResult;
	}

	/**
	 * 导出
	 * 
	 * @param queryMap
	 * @param response
	 */
	public void exportInquiryList(Map<String, Object> queryMap, HttpServletResponse response) {
		SysUser sysUser = SpringMvcUtils.getSysUser();

		if (!sysUser.getSuperadmin().equals(Global.YES + "")) {
			if (StringUtils.isNotNull(sysUser.getDatapermission())) {
				queryMap.put("deptIds", sysUser.getDatapermission().split(","));
			} else {
				queryMap.put("createId", sysUser.getUserid());
			}
		}
		List<PurchaseInquiry> list = inquiryMapper.selectInquiryList(queryMap);

		logger.info("exportInquiryList:{}", list);

		try {
			EasyExcel.write(response.getOutputStream(), PurchaseInquiry.class).sheet("模板").doWrite(list);
		} catch (IOException e) {
			logger.error("导出错误:{}", e.getMessage());
		}

	}

	/**
	 * 询价详情
	 * 
	 * @param inqId
	 * @return
	 */
	public HttpResult selectInquiry(String inqId) {
		HttpResult httpResult = new HttpResult();
//		PurchaseInquiryVO purchaseInquiryVO = new PurchaseInquiryVO();
		PurchaseInquiryVO purchaseInquiryVO = inquiryMapper.selectVO(inqId);
		if (purchaseInquiryVO != null) {
			HashMap<String, Object> hashMap = new HashMap<String, Object>();
			hashMap.put("inqId", inqId);
			// 供应商
			List<PurchaseSupplyOffer> purchaseSupplyOffers = supplyOfferMapper.selectSupplyOfferList(hashMap);
			purchaseSupplyOffers = purchaseSupplyOffers.stream()
					.sorted(Comparator.comparing(PurchaseSupplyOffer::getInqOfrTotalPrice,
							Comparator.nullsLast(Comparator.naturalOrder())))
					.collect(Collectors.toList());
			purchaseInquiryVO.setPurchaseSupplyOffers(purchaseSupplyOffers);
			// 报价明细
			List<PurchaseSupplyOfferMm> purchaseSupplyOfferMms = supplyOfferMmMapper.selectAll(hashMap);
			purchaseInquiryVO.setPurchaseSupplyOfferMms(purchaseSupplyOfferMms);
			// 物资明细
			hashMap.put("gramId", purchaseInquiryVO.getGramId());
			List<PurchaseProgramMm> purchaseProgramMms = programMmMapper.selectProgramMmList(hashMap);
			purchaseInquiryVO.setPurchaseProgramMms(purchaseProgramMms);
		}
		logger.info("selectInquiry:{}", purchaseInquiryVO);
		httpResult.setData(purchaseInquiryVO);
		httpResult.setCode(HttpStatus.SUCCESS_CODE);
		return httpResult;
	}

	/**
	 * 保存询价书
	 *
	 * @param purchaseInquiryVO
	 * @return
	 */
	@Transactional
	public HttpResult saveInquiry(PurchaseInquiryVO purchaseInquiryVO) {
		if (purchaseInquiryVO == null || purchaseInquiryVO.getPurchaseProgramMms() == null) {
			return HttpResult.error("参数不能为空!");
		}

		HttpResult httpResult = new HttpResult();
		SysUser sysUser = SpringMvcUtils.getSysUser();

		String inqIdString = purchaseInquiryVO.getInqId();
		if (!StringUtils.isNotNull(inqIdString)) {
			String idString = UUID.randomUUID().toString();
			purchaseInquiryVO.setInqId(idString);
			purchaseInquiryVO.setInqCode(commonService.createCode("purchase_inquiry", "inq_code"));
		}

		int result = 0;
		// 主表保存
		if (!StringUtils.isNotNull(inqIdString)) {
			result = inquiryMapper.insert(purchaseInquiryVO);
		} else {
			result = inquiryMapper.update(purchaseInquiryVO);
		}

		if (purchaseInquiryVO.getStatus().equals(Global.YES + "")) {
			if (purchaseInquiryVO.getInqOfferMode().equals(OfferModeEnum.jj.getValue())) {
				PurchaseProgram purchaseProgram = programMapper.load(purchaseInquiryVO.getGramId());
				supplyCompeteDao.deleteByInqId(purchaseInquiryVO.getInqId());
				supplyCompeteMmDao.deleteByInqId(purchaseInquiryVO.getInqId());
				for (PurchaseSupplyOffer purchaseSupplyOffer : purchaseInquiryVO.getPurchaseSupplyOffers()) {
					SupplyCompeteModel supplyCompeteModel = new SupplyCompeteModel();
					BeanUtils.copyProperties(purchaseSupplyOffer, supplyCompeteModel);
					SupplyInfoModel supplyInfoModel = infoMapper.load(purchaseSupplyOffer.getInfId());
					supplyCompeteModel.setInqCode(purchaseInquiryVO.getInqCode());
					supplyCompeteModel.setInqId(purchaseInquiryVO.getInqId());
					supplyCompeteModel.setInqStartTime(purchaseInquiryVO.getInqStartTime());
					supplyCompeteModel.setInqEndTime(purchaseInquiryVO.getInqEndTime());
					supplyCompeteModel.setInqName(purchaseInquiryVO.getInqName());
					supplyCompeteModel.setInqMode(purchaseInquiryVO.getInqOfferMode());
					supplyCompeteModel.setCreateId(sysUser.getUserid());// 小心被替换为供应商创建人
					supplyCompeteModel.setCreateName(sysUser.getUsername());
					supplyCompeteModel.setCreateTime(DateUtils.getCurrentTime());
					supplyCompeteModel.setStatus(Global.NO + "");
					supplyCompeteModel.setInfContact(supplyInfoModel.getInfContactsName());
					supplyCompeteModel.setInfContactTel(supplyInfoModel.getInfMobile());
					supplyCompeteModel.setGramAmplitude(purchaseProgram.getGramAmplitude());
					supplyCompeteModel.setGramTimes(purchaseProgram.getGramTimes());
					supplyCompeteModel.setGramDealMode(purchaseProgram.getGramDealMode());
					supplyCompeteModel.setGramId(purchaseProgram.getGramId());
					supplyCompeteModel.setId(UUID.randomUUID().toString());
					supplyCompeteModel.setLowStatus(Global.NO + "");
					supplyCompeteDao.insert(supplyCompeteModel);
					// 明细保存
					for (PurchaseProgramMm programMm : purchaseInquiryVO.getPurchaseProgramMms()) {
						SupplyCompeteMmModel supplyCompeteMmModel = new SupplyCompeteMmModel();
						supplyCompeteMmModel.setInqId(purchaseInquiryVO.getInqId());
						supplyCompeteMmModel.setInfId(purchaseSupplyOffer.getInfId());
						supplyCompeteMmModel.setPlanId(programMm.getPlanId());
						supplyCompeteMmModel.setMmCode(programMm.getMmCode());
						supplyCompeteMmModel.setMmDetail(programMm.getMmDetail());
						supplyCompeteMmModel.setMmUnit(programMm.getMmUnit());
						supplyCompeteMmModel.setMmUnitDetail(programMm.getMmUnitDetail());
						supplyCompeteMmModel.setPlanFactoryCode(programMm.getPlanFactoryCode());
						supplyCompeteMmModel.setGramPurNum(programMm.getGramPurNum());
						supplyCompeteMmModel.setCreateTime(DateUtils.getCurrentTime());
						supplyCompeteMmModel.setGramUseName(programMm.getGramUseName());
						supplyCompeteMmModel.setGramUseTel(programMm.getGramUseTel());
						supplyCompeteMmModel.setGramId(programMm.getGramId());
						supplyCompeteMmDao.insert(supplyCompeteMmModel);
						programMm.setStatus(Global.NUMERICAL_TWO + "");
						programMmMapper.update(programMm);
					}
				}
			} else {
				// 报价表保存
				if (purchaseInquiryVO.getPurchaseSupplyOffers() != null) {
					supplyOfferMapper.deleteByInqId(purchaseInquiryVO.getInqId());
					for (PurchaseSupplyOffer purchaseSupplyOffer : purchaseInquiryVO.getPurchaseSupplyOffers()) {
						SupplyInfoModel supplyInfoModel = infoMapper.load(purchaseSupplyOffer.getInfId());
						purchaseSupplyOffer.setId(UUID.randomUUID().toString());
						purchaseSupplyOffer.setInqCode(purchaseInquiryVO.getInqCode());
						purchaseSupplyOffer.setInqId(purchaseInquiryVO.getInqId());
						purchaseSupplyOffer.setInqStartTime(purchaseInquiryVO.getInqStartTime());
						purchaseSupplyOffer.setInqEndTime(purchaseInquiryVO.getInqEndTime());
						purchaseSupplyOffer.setInqName(purchaseInquiryVO.getInqName());
						purchaseSupplyOffer.setInqMode(purchaseInquiryVO.getInqOfferMode());
						purchaseSupplyOffer.setCreateId(sysUser.getUserid());// 小心被替换为供应商创建人
						purchaseSupplyOffer.setCreateName(sysUser.getUsername());
						purchaseSupplyOffer.setCreateTime(DateUtils.getCurrentTime());
						purchaseSupplyOffer.setStatus(Global.NO + "");
						purchaseSupplyOffer.setInfContact(supplyInfoModel.getInfContactsName());
						purchaseSupplyOffer.setInfContactTel(supplyInfoModel.getInfMobile());
						supplyOfferMapper.insert(purchaseSupplyOffer);
						// 报价明细保存
						supplyOfferMmMapper.deleteByInqIdAndInfId(purchaseInquiryVO.getInqId(),
								purchaseSupplyOffer.getInfId());
						for (PurchaseProgramMm programMm : purchaseInquiryVO.getPurchaseProgramMms()) {
							PurchaseSupplyOfferMm purchaseSupplyOfferMm = new PurchaseSupplyOfferMm();
							purchaseSupplyOfferMm.setInqId(purchaseInquiryVO.getInqId());
							purchaseSupplyOfferMm.setInfId(purchaseSupplyOffer.getInfId());
							purchaseSupplyOfferMm.setPlanId(programMm.getPlanId());
							purchaseSupplyOfferMm.setMmCode(programMm.getMmCode());
							purchaseSupplyOfferMm.setMmDetail(programMm.getMmDetail());
							purchaseSupplyOfferMm.setMmUnit(programMm.getMmUnit());
							purchaseSupplyOfferMm.setMmUnitDetail(programMm.getMmUnitDetail());
							purchaseSupplyOfferMm.setPlanFactoryCode(programMm.getPlanFactoryCode());
							purchaseSupplyOfferMm.setGramPurNum(programMm.getGramPurNum());
							purchaseSupplyOfferMm.setCreateTime(DateUtils.getCurrentTime());
							purchaseSupplyOfferMm.setGramUseName(programMm.getGramUseName());
							purchaseSupplyOfferMm.setGramUseTel(programMm.getGramUseTel());
							purchaseSupplyOfferMm.setMmMain(programMm.getMmMain());
							supplyOfferMmMapper.insert(purchaseSupplyOfferMm);
							programMm.setStatus(Global.NUMERICAL_TWO + "");
							programMmMapper.update(programMm);
						}
					}
				}
			}
			// 将采购方案状态改为以生成
			PurchaseProgram program = programMapper.load(purchaseInquiryVO.getGramId());
			program.setStatus(Global.NUMERICAL_TWO + "");
			programMapper.update(program);
		}
		if (result > 0) {
			httpResult.setMsg(purchaseInquiryVO.getStatus().equals(Global.YES + "") ? "提交成功!" : "保存成功!");
			httpResult.setData(purchaseInquiryVO);
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg(purchaseInquiryVO.getStatus().equals(Global.YES + "") ? "提交失败!" : "保存失败!");
		}
		return httpResult;
	}

	/**
	 * 删除询价书
	 *
	 * @param inqId
	 * @return
	 */
	@Transactional
	public HttpResult delInquiry(String inqId) {
		HttpResult httpResult = new HttpResult();
		if (!StringUtils.isNotNull(inqId)) {
			return HttpResult.error("参数不能为空");
		}
		PurchaseInquiry model = inquiryMapper.load(inqId);
		if (!model.getStatus().equals(Global.NO + "")) {
			return HttpResult.error("非待提交状态，不可删除！");
		}
		int result = inquiryMapper.delete(inqId);
		supplyOfferMapper.deleteByInqId(inqId);
		supplyOfferMmMapper.deleteByInqId(inqId);
		supplyCompeteDao.deleteByInqId(inqId);
		supplyCompeteMmDao.deleteByInqId(inqId);

		if (result > 0) {
			httpResult.setMsg("删除成功！");
			httpResult.setCode(HttpStatus.SUCCESS_CODE);
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg("不存在此条询价书！");
		}
		return httpResult;
	}

	/**
	 * 回退
	 *
	 * @param purchaseInquiryVO
	 * @return
	 */
	@Transactional
	public HttpResult backInquiry(PurchaseInquiryVO purchaseInquiryVO) {
		if (purchaseInquiryVO == null) {
			return HttpResult.error("参数不能为空");
		}
		if (StringUtils.isNotNull(purchaseInquiryVO.getInqActualTime())) {
			return HttpResult.error("报价已揭示，不可回退!");
		}

		int result = 0;
		purchaseInquiryVO.setStatus(Global.NO + "");
		result = inquiryMapper.update(purchaseInquiryVO);

		// 采购方案状态改变
		PurchaseProgram purchaseProgram = programMapper.load(purchaseInquiryVO.getGramId());
		purchaseProgram.setStatus(Global.YES + "");
		programMapper.update(purchaseProgram);

		// 删除供应商报价信息
		supplyOfferMapper.deleteByInqId(purchaseInquiryVO.getInqId());
		supplyOfferMmMapper.deleteByInqId(purchaseInquiryVO.getInqId());
		// 删除竞价信息
		supplyCompeteDao.deleteByInqId(purchaseInquiryVO.getInqId());
		supplyCompeteMmDao.deleteByInqId(purchaseInquiryVO.getInqId());

		HttpResult httpResult = new HttpResult();
		if (result > 0) {
			httpResult.setMsg("回退成功！");
			httpResult.setCode(HttpStatus.SUCCESS_CODE);
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg("回退失败！");
		}
		return httpResult;
	}

}
